#!/bin/bash
#
# Author:   Dr. Mike Murphy (mmurphy2@coastal.edu)
# Revision: 13 November 2013
#
#   Copyright 2012-2013 Coastal Carolina University
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#


## p_agent_hostname_help
##
## Echoes help information for the Hostname agent. Returns 0.
##
function p_agent_hostname_help() {
	cat << EOF
Updates the system hostname and adjusts the DHCP_HOSTNAME flag in the
system network configuration scripts. Presently, DHCP_HOSTNAME support is
limited to Red Hat compatible hosts.

In check-only mode, checks to see if the system hostname matches the
hostname supplied by the subscription (if any).
EOF
	return 0
}


## p_agent_hostname_summary
##
## Echoes summary information for the Hostname agent. Returns 0.
##
function p_agent_hostname_summary() {
	echo "Updates system hostname"
	return 0
}


## p_agent_hostname_check
##
## Checks to determine whether or not the current system hostname matches
## the requested hostname (if any). Returns 0 if the Pulley subscription does
## not specify a hostname, or if the hostname already matches the subscription
## request. Returns 100 if the system hostname differs from the requested
## hostname.
##
function p_agent_hostname_check() {
	local current_hostname=$(hostname)
	local rq_hostname=$(get_context agent/hostname/hostname)
	local status=0
	
	if [ -n "${rq_hostname}" ]; then
		if [ "${current_hostname}" != "${rq_hostname}" ]; then
			status=100
		fi
	fi
	
	return ${status}
}


## p_agent_hostname_run
##
## Implements the mechanisms to run the Hostname agent, checking and updating
## the system hostname from the Pulley subscription. Returns 0 on success,
## non-zero if an error occurs.
##
function p_agent_hostname_run() {
	local status=0
	p_agent_hostname_check
	if [ $? -eq 100 ]; then
		local rq_hostname=$(get_context agent/hostname/hostname)
		local platform=$(get_context platform/name)
		
		if [[ -f "${P_LIBDIR}/platforms/${platform}/hostname.support" ]]; then
			. "${P_LIBDIR}/platforms/${platform}/hostname.support"
			p_agent_hostname_${platform}_set_hostname "${rq_hostname}"
			status=$?
		else
			echo "Platform not supported for hostname changes."
			status=4
		fi
	fi
	
	return ${status}
}
